package com.milepost.workflow.flowdef.ctrl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.milepost.workflow.common.dto.BootstrapTableVoDto;
import com.milepost.workflow.common.enums.DsKeyEnum;
import com.milepost.workflow.common.vo.BootstrapTableVo;
import com.milepost.workflow.config.dynamicDs.DataSourceContextHolder;
import com.milepost.workflow.flowdef.dto.FlowDefDto;
import com.milepost.workflow.flowdef.entity.FlowDefEntity;
import com.milepost.workflow.flowdef.service.FlowDefService;
import com.milepost.workflow.flowdeftask.entity.FlowDefTaskEntity;
import com.milepost.workflow.response.Response;
import com.milepost.workflow.response.ResponseHelper;
import com.milepost.workflow.response.ReturnCode;
import com.milepost.workflow.user.entity.UsersEntity;
import com.milepost.workflow.user.service.UserService;
import com.milepost.workflow.util.SessionUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author huarf
 * @Description
 * @create 2022-03-24 13:50
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/flowDef")
public class FlowDefCtrl {

    private final FlowDefService flowDefService;

    private final UserService userService;

    /**
     * 判断当前流程是否已经制作了流程表单，
     * 判断当前流程中是否有指定型任务，
     * @param id
     * @return
     */
    @GetMapping("/check")
    public Response<Map<String, Boolean>> check(String id) {

        Response<Map<String, Boolean>> response = null;

        try {
            boolean hasPointTask = flowDefService.hasPointTask(id);
            boolean hasFlowDefForm = flowDefService.hasFlowDefForm(id);
            Map<String, Boolean> payloadMap = new HashMap<>();
            payloadMap.put("hasPointTask", hasPointTask);
            payloadMap.put("hasFlowDefForm", hasFlowDefForm);
            response = ResponseHelper.createSuccessResponse(payloadMap);
        } catch (Exception e) {
            log.error("获取流程是否有pointTask类型任务异常", e);
            response = ResponseHelper.createExceptionResponse(e);
        }

        return response;
    }

    /**
     * 修改工作流
     *
     * @param flowDefDto
     * @return
     */
    @PostMapping("/modifyFlowDef")
    public Response<?> modifyFlowDef(@RequestBody FlowDefDto flowDefDto) {

        Response<?> response = null;

        try {
            boolean success = flowDefService.modifyFlowDef(flowDefDto);
            if (success) {
                response = ResponseHelper.createResponse(ReturnCode.SUCCESS, "修改流程成功");
            } else {
                response = ResponseHelper.createResponse(ReturnCode.FAIL, "修改流程失败");
            }
        } catch (Exception e) {
            log.error("修改流程异常", e);
            response = ResponseHelper.createExceptionResponse(e);
        }

        return response;
    }

    /**
     * 查看流程
     *
     * @param id
     * @return
     */
    @GetMapping("/getById")
    public Response<FlowDefDto> getById(String id) {

        Response<FlowDefDto> response = null;

        try {
            FlowDefDto flowDefDto = flowDefService.getFlowDefById(id);
            if (flowDefDto != null) {
                // 填充用户名称
                DataSourceContextHolder.setDataSource(DsKeyEnum.USER.getKey());
                List<FlowDefTaskEntity> flowDefTaskEntityList = flowDefDto.getFlowDefTaskEntityList();
                for (FlowDefTaskEntity flowDefTaskEntity : flowDefTaskEntityList) {
                    String assignees = flowDefTaskEntity.getAssignees();
                    if (StringUtils.isNoneBlank(assignees)) {
                        String assigneesName = userService.getUserNamesByIds(assignees);
                        flowDefTaskEntity.setAssigneesName(assigneesName);
                    }
                }
                response = ResponseHelper.createSuccessResponse(flowDefDto);
            } else {
                response = ResponseHelper.createResponse(ReturnCode.FAIL, "查看流程失败");
            }
        } catch (Exception e) {
            log.error("查看流程异常", e);
            response = ResponseHelper.createExceptionResponse(e);
        } finally {
            DataSourceContextHolder.clearDataSource();
        }

        return response;
    }

    /**
     * 删除流程
     *
     * @param id
     * @return
     */
    @DeleteMapping("/deleteById")
    public Response<?> deleteById(String id) {

        Response<?> response = null;

        try {
            boolean success = flowDefService.deleteById(id);
            if (success) {
                response = ResponseHelper.createResponse(ReturnCode.SUCCESS, "删除流程成功");
            } else {
                response = ResponseHelper.createResponse(ReturnCode.FAIL, "删除流程失败");
            }
        } catch (Exception e) {
            log.error("删除流程异常", e);
            response = ResponseHelper.createExceptionResponse(e);
        }

        return response;
    }

    /**
     * 查询流程列表
     *
     * @param bootstrapTableVoDto
     * @param flowDefEntity
     * @return
     */
    @GetMapping("/getFlowDefList")
    public Response<BootstrapTableVo<FlowDefEntity>> getFlowDefList(BootstrapTableVoDto bootstrapTableVoDto, FlowDefEntity flowDefEntity, HttpSession session) {

        Response<BootstrapTableVo<FlowDefEntity>> response = null;

        try {
            UsersEntity currUser = SessionUtil.getCurrUser(session);
            log.info("当前登录用户：" + currUser);

            Page<FlowDefEntity> flowDefEntityPage = flowDefService.getFlowDefList(bootstrapTableVoDto, flowDefEntity);
            // 填充用户名称
            DataSourceContextHolder.setDataSource(DsKeyEnum.USER.getKey());
            for (FlowDefEntity record : flowDefEntityPage.getRecords()) {
                if (StringUtils.isNoneBlank(record.getCrtUser())) {
                    UsersEntity userEntity = userService.getById(record.getCrtUser());
                    if (userEntity != null) {
                        record.setCrtUserName(userEntity.getName());
                    }
                }
            }

            BootstrapTableVo<FlowDefEntity> bootstrapTableVo = new BootstrapTableVo<>(flowDefEntityPage);
            response = ResponseHelper.createSuccessResponse(bootstrapTableVo);
        } catch (Exception e) {
            log.error("查询流程列表异常", e);
            response = ResponseHelper.createExceptionResponse(e);
        } finally {
            DataSourceContextHolder.clearDataSource();
        }

        return response;
    }

    /**
     * 创建工作流
     *
     * @param flowDefDto
     * @return
     */
    @PostMapping("/createFlowDef")
    public Response<?> createFlowDef(@RequestBody FlowDefDto flowDefDto, HttpSession session) {

        Response<?> response = null;

        try {
            flowDefDto.getFlowDefEntity().setCrtUser(SessionUtil.getCurrUser(session).getId());
            boolean success = flowDefService.createFlowDef(flowDefDto);
            if (success) {
                response = ResponseHelper.createResponse(ReturnCode.SUCCESS, "创建流程成功");
            } else {
                response = ResponseHelper.createResponse(ReturnCode.FAIL, "创建流程失败");
            }
        } catch (Exception e) {
            log.error("创建流程异常", e);
            response = ResponseHelper.createExceptionResponse(e);
        }

        return response;
    }

}
